import { NextRequest, NextResponse } from 'next/server';
import { revalidatePath, revalidateTag } from 'next/cache';

// 部署配置
const DEPLOY_CONFIG = {
  production: {
    baseUrl: process.env.NEXT_PUBLIC_BASE_URL || 'https://your-production-domain.com',
    pagesToRevalidate: ['/', '/about', '/user/1', '/realtime', '/admin'],
    tagsToRevalidate: ['products', 'articles', 'users', 'config']
  },
  staging: {
    baseUrl: process.env.NEXT_PUBLIC_STAGING_URL || 'https://your-staging-domain.com',
    pagesToRevalidate: ['/', '/about'],
    tagsToRevalidate: ['products', 'articles']
  }
};

// 验证部署webhook签名（以Vercel为例）
function verifyDeploySignature(request: NextRequest, body: string): boolean {
  const signature = request.headers.get('x-vercel-signature');
  const secret = process.env.VERCEL_DEPLOY_HOOK_SECRET;
  
  if (!signature || !secret) {
    return false;
  }
  
  // 这里应该实现实际的签名验证逻辑
  // 为了演示，我们简化处理
  return true;
}

// 处理Vercel部署webhook
async function handleVercelDeploy(body: any) {
  const { deployment } = body;
  
  if (!deployment) {
    throw new Error('无效的部署数据');
  }
  
  console.log(`🚀 Vercel部署触发 - 环境: ${deployment.target}, 状态: ${deployment.readyState}`);
  
  // 只在部署成功时重新验证
  if (deployment.readyState !== 'READY') {
    console.log('⏳ 部署尚未完成，跳过重新验证');
    return { skipped: true, reason: '部署未完成' };
  }
  
  const config = DEPLOY_CONFIG[deployment.target as keyof typeof DEPLOY_CONFIG];
  if (!config) {
    throw new Error(`未知的部署环境: ${deployment.target}`);
  }
  
  return await performRevalidation(config);
}

// 处理Netlify部署webhook
async function handleNetlifyDeploy(body: any) {
  const { site_name, url, deploy_time } = body;
  
  console.log(`🚀 Netlify部署触发 - 站点: ${site_name}, URL: ${url}`);
  
  // 使用生产环境配置
  const config = DEPLOY_CONFIG.production;
  return await performRevalidation(config);
}

// 处理GitHub Actions部署webhook
async function handleGitHubDeploy(body: any) {
  const { repository, workflow_run } = body;
  
  console.log(`🚀 GitHub Actions部署触发 - 仓库: ${repository?.name}, 工作流: ${workflow_run?.name}`);
  
  // 检查工作流状态
  if (workflow_run?.conclusion !== 'success') {
    console.log('⏳ 工作流未成功完成，跳过重新验证');
    return { skipped: true, reason: '工作流未成功' };
  }
  
  const config = DEPLOY_CONFIG.production;
  return await performRevalidation(config);
}

// 执行重新验证
async function performRevalidation(config: any) {
  const results = {
    pages: [] as any[],
    tags: [] as any[],
    summary: {
      totalPages: config.pagesToRevalidate.length,
      totalTags: config.tagsToRevalidate.length,
      successfulPages: 0,
      successfulTags: 0,
      failedPages: 0,
      failedTags: 0
    }
  };
  
  console.log('📄 开始重新验证页面...');
  
  // 重新验证页面
  for (const path of config.pagesToRevalidate) {
    try {
      revalidatePath(path);
      console.log(`✅ 页面重新验证成功: ${path}`);
      results.pages.push({ success: true, path });
      results.summary.successfulPages++;
    } catch (error) {
      console.error(`❌ 页面重新验证失败: ${path}`, error);
      results.pages.push({ success: false, path, error: error instanceof Error ? error.message : '未知错误' });
      results.summary.failedPages++;
    }
  }
  
  console.log('🏷️  开始重新验证缓存标签...');
  
  // 重新验证标签
  for (const tag of config.tagsToRevalidate) {
    try {
      revalidateTag(tag);
      console.log(`✅ 标签重新验证成功: ${tag}`);
      results.tags.push({ success: true, tag });
      results.summary.successfulTags++;
    } catch (error) {
      console.error(`❌ 标签重新验证失败: ${tag}`, error);
      results.tags.push({ success: false, tag, error: error instanceof Error ? error.message : '未知错误' });
      results.summary.failedTags++;
    }
  }
  
  return results;
}

export async function POST(request: NextRequest) {
  try {
    // 获取请求体
    const body = await request.json();
    
    // 验证请求来源
    const userAgent = request.headers.get('user-agent') || '';
    const contentType = request.headers.get('content-type') || '';
    
    console.log(`🔐 部署webhook请求 - User-Agent: ${userAgent}`);
    
    let results;
    
    // 根据请求来源处理不同类型的部署webhook
    if (userAgent.includes('Vercel') || body.deployment) {
      // Vercel部署webhook
      if (!verifyDeploySignature(request, JSON.stringify(body))) {
        return NextResponse.json({ error: '签名验证失败' }, { status: 401 });
      }
      results = await handleVercelDeploy(body);
    } else if (userAgent.includes('Netlify') || body.site_name) {
      // Netlify部署webhook
      results = await handleNetlifyDeploy(body);
    } else if (userAgent.includes('GitHub') || body.repository) {
      // GitHub Actions部署webhook
      results = await handleGitHubDeploy(body);
    } else {
      // 通用部署webhook
      console.log('🚀 通用部署webhook触发');
      const config = DEPLOY_CONFIG.production;
      results = await performRevalidation(config);
    }
    
    // 记录部署日志
    console.log('📊 部署重新验证结果:', JSON.stringify(results, null, 2));
    
    return NextResponse.json({
      success: true,
      message: '部署webhook处理成功',
      results,
      timestamp: new Date().toISOString()
    });
    
  } catch (error) {
    console.error('❌ 部署webhook处理失败:', error);
    return NextResponse.json({
      error: '部署webhook处理失败',
      details: error instanceof Error ? error.message : '未知错误',
      timestamp: new Date().toISOString()
    }, { status: 500 });
  }
}

// 支持GET请求用于测试
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const test = searchParams.get('test');
  
  if (test === 'true') {
    console.log('🧪 测试部署webhook');
    const config = DEPLOY_CONFIG.production;
    const results = await performRevalidation(config);
    
    return NextResponse.json({
      success: true,
      message: '测试部署webhook成功',
      results,
      timestamp: new Date().toISOString()
    });
  }
  
  return NextResponse.json({
    message: '部署webhook端点',
    usage: 'POST /api/deploy-webhook 或 GET /api/deploy-webhook?test=true',
    timestamp: new Date().toISOString()
  });
}
